import pandas


class Store(object):
    columns = []

    def __init__(self):
        self.dataframe = pandas.DataFrame(columns=self.columns)

    def query(self, **kwargs):
        dataframe = self.dataframe
        for key, filters in kwargs.items():
            for operator, value in filters.items():
                dataframe = dataframe.loc[getattr(dataframe[key], operator)(value)]
        return dataframe

    def insert(self, **kwargs):
        self.dataframe = pandas.concat([self.dataframe, pandas.DataFrame([kwargs])], ignore_index=True)
        return self.dataframe.iloc[-1]

    def update(self, updates, **kwargs):
        dataframe = self.query(**kwargs)
        updated = len(dataframe.index)
        if updated:
            self.dataframe.loc[dataframe.index, updates.keys()] = list(updates.values())
        return self.dataframe.loc[dataframe.index]

    def update_or_insert(self, updates, **kwargs):
        dataframe = self.query(**kwargs)
        created, updated = None, len(dataframe.index)
        if updated:
            self.dataframe.loc[dataframe.index, updates.keys()] = list(updates.values())
        else:
            created = self.insert(**updates)
        return created, updated

    def delete(self, **kwargs):
        dataframe = self.query(**kwargs)
        dropped = len(dataframe.index)
        if dropped:
            self.dataframe.drop(index=dataframe.index, inplace=True)
        return dropped

    def append(self, dataframe: pandas.DataFrame):
        self.dataframe = pandas.concat([self.dataframe, dataframe])
        self.dataframe = self.dataframe.reset_index(drop=True)


__all__ = [Store]
